package com.ustadzmenjawab.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBConnFactory {

	private static DataSource pool;
	public static final boolean USE_DATA_SOURCE = true;
//	static{
//		if(USE_DATA_SOURCE){
//			Context env = null;
//			try {
//				String dbname = "the_great_nelman";
//				env = (Context) new InitialContext().lookup("java:comp/env");
//				if(env != null){
//					pool = (DataSource) env.lookup("jdbc/"+dbname);
//					if(pool == null){
//						throw new NamingException("'"+dbname+"' is an unknown datasource");
//					}
//				}
//			} catch (NamingException e) {
//
//				e.printStackTrace();
//			}
//		}
//
//	}
	public static void initDataSource(){
		if(USE_DATA_SOURCE){
			Context env = null;
			try {
				String dbname = "the_great_nelman";
				env = (Context) new InitialContext().lookup("java:comp/env");
				if(env != null){
					pool = (DataSource) env.lookup("jdbc/"+dbname);
					if(pool == null){
						throw new NamingException("'"+dbname+"' is an unknown datasource");
					}
				}else{
					throw new NamingException("Look up java:comp/env could not get env");
				}
			} catch (NamingException e) {

				e.printStackTrace();
			}
		}
	}
	
	public static Connection getConnection(){
		return getConnectionWithDataSource();
		//return getConnectionWODataSource();
	}
	public static Connection getConnectionWithDataSource(){
		try {
			if(pool == null){
				initDataSource();
			}
			Connection conn =pool.getConnection();
			return conn;
		}  catch (SQLException e) {
			e.printStackTrace();
		} 
		return null;
	}
	public static Connection getConnectionWODataSource(){
		try{
			String jdbc = "jdbc:mysql://localhost:3306/the_great_nelman";
			String user = "root";
			String pass = "";

			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection(jdbc, user, pass);
			return conn;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public static void closeConnection(Connection conn){
		try {
			if(!conn.isClosed())
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
